package com.huaxin.device.feignClients.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huaxin.device.feignClients.SysFeignService;
import com.huaxin.feignclient.models.ResponseCode;
import com.huaxin.feignclient.system.SystemClient;
import com.huaxin.feignclient.system.models.ElectricianScopeDTO;
import com.huaxin.feignclient.system.models.Family;
import com.huaxin.feignclient.system.models.SysDictionary;
import com.huaxin.feignclient.system.models.User;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class SysFeignServiceImpl implements SysFeignService {
    private final SystemClient systemClient;
    private final ObjectMapper objectMapper;

    /**
     * 获取用户信息
     */
    @Override
    public User getUserInfoById(String userId) {
        com.huaxin.feignclient.models.ResponseResult<User> userInfo = systemClient.getUserInfoById(userId);
        if (userInfo.getCode() != ResponseCode.SUCCESS.getCode() || userInfo.getData() == null) {
            return null;
        }
        return userInfo.getData();
    }

    /**
     * 获取报警检测周期
     */
    @Override
    public String getAlarmDetectInterval() {
        String alarmDetectInterval = "0 0/3 * * * ?";
        try {
            com.huaxin.feignclient.models.ResponseResult<SysDictionary> alarmDetectIntervalResult = systemClient.querySystemDictByKey("alarm_detect_interval");
            if (alarmDetectIntervalResult.getCode() != ResponseCode.SUCCESS.getCode() || alarmDetectIntervalResult.getData() == null) {
                return alarmDetectInterval;
            }
            JsonNode root = objectMapper.readTree(alarmDetectIntervalResult.getData().getDictValue());
            alarmDetectInterval = root.get("cron").asText(); // 提取 cron 值
        } catch (Exception ignored) {
        }
        return alarmDetectInterval;
    }

    @Override
    public Family getFamilyById(String familyId) {
        com.huaxin.feignclient.models.ResponseResult<Family> family = systemClient.getFamilyById(familyId);
        if (family.getCode() != ResponseCode.SUCCESS.getCode() || family.getData() == null) {
            return null;
        }
        return family.getData();
    }

    /**
     * 获取电工与组织和家庭的关系
     */
    @Override
    public List<ElectricianScopeDTO> electricianScopeList(String electricianId) {
        com.huaxin.feignclient.models.ResponseResult<List<ElectricianScopeDTO>> electricianScopeList = systemClient.electricianScopeList(electricianId);
        if (electricianScopeList.getCode() != ResponseCode.SUCCESS.getCode() || electricianScopeList.getData() == null) {
            return null;
        }
        return electricianScopeList.getData();
    }
}
